# ADMIN: Used to add/remove/edit matches

class Admin::MatchesController < Admin::BaseController
  def index
    @search = Match.new_search params[:search] do |search|
      search.conditions.home_team.name_contains = params[:name]
      search.conditions.played = !!params[:played]
      #search.conditions.away_team.or_name_contains = params[:name]
    end
    @search.order_by = "id"
    @search.order_as = "desc"
    @matches = @search.all #:page=>params[:page],:order=>"id desc"
    @next_match = Match.next_match
  end

  def destroy
    @match = Match.find params[:id]
    @match.destroy
    flash[:notice] = "match was deleted"
    redirect_to admin_matches_path
  end

  def update
    @match = Match.find params[:id]
    if @match.update_attributes params[:match]
      flash[:notice] = 'Match was updated.'
      redirect_to admin_matches_path
    else
      @sport = @match.sport
      render :action=>"edit"
    end
  end

  def new
    @match = Match.new
    if params[:sport_id]
      @sport = Sport.find_by_id(params[:sport_id])
      @match.sport = @sport
    else
      render :template=>"admin/matches/select_sport"
    end
  end

  def create
    @match = Match.new params[:match]
    if @match.save
      flash[:notice] = "match was created."
      redirect_to admin_matches_path
    else
      @sport = @match.sport
      render :action=>"new"
    end
  end

  def edit
    @match = Match.find params[:id]
    @sport = @match.sport
  end

  def play
    @match = Match.find params[:id]
  end

  # set play result , and process bets , etc..
  def do_play
    @match = Match.find params[:id]
    @match.update_attributes params[:match]
    @match.save
    begin
      @match.play_from_point
      flash[:notice] = "success played."
    rescue Exception=>e
      logger.error e.backtrace.join("\n")
      flash[:error] = e.message
      return redirect_to(play_admin_match_path(@match))
    end
    redirect_to admin_matches_path
  end

end
